package cn.mdmm.service.impl.weixin;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.weixin.config.WxConfig;
import com.weixin.core.TokenFactory;
import com.weixin.utils.WxWeb;

import cn.mdmm.entity.user.WxUserDetailedInfoModel;
import cn.mdmm.mapper.weixin.WxUserDetailedInfoMapper;
import cn.mdmm.service.user.WxUserDetailedInfoService;
import cn.modoumama.service.base.impl.BaseServiceImpl;

/**
 * 项目名称：Health_Scale_Service  
 *  
 * 类名称：com.daboo.mysql.temp.service.WxUserDetailedInfoServiceImpl
 * 类描述：微信用户管理实现类
 * 创建人：邓强
 * 创建时间：2016-10-10 下午3:28:40   
 * 修改人：  
 * 修改时间：  
 * 修改备注：     
 * @version   V1.0      
 */
@Service
public class WxUserDetailedInfoServiceImpl extends BaseServiceImpl<WxUserDetailedInfoModel, Integer> implements WxUserDetailedInfoService{
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	public void setMapper(WxUserDetailedInfoMapper genericMapper) {
		super.setGenericMapper(genericMapper);
	}
	
	@Override
	public WxUserDetailedInfoModel getWxUserDetailedInfoByOpenId(String openId) {
		WxUserDetailedInfoModel wxUserDetailedInfoModel = new WxUserDetailedInfoModel();
		wxUserDetailedInfoModel.setOpenId(openId);
		return getObjectByModel(wxUserDetailedInfoModel);
	}

	@Override
	public WxUserDetailedInfoModel insertWxUserDetailedInfo(Map<String, Object> model) {
		String openid = (String) model.get("openid");
		if(null != model && StringUtils.isNotBlank(openid)){
			Set<String> keys = model.keySet();
			WxUserDetailedInfoModel newModel = new WxUserDetailedInfoModel();
			//把model转换成对象
			for (String key : keys) {
				String fieldName = null;
				switch (key) {
					case "privilege":
					continue;
					case "nickname":
						fieldName = "nickName";
						break;
					case "openid":
						fieldName = "openId";
						break;
					case "headimgurl":
						fieldName = "headImgUrl";
						break;
					default:
						fieldName = key;
					break;	
				}
				Field field = null;
					try {
						field = WxUserDetailedInfoModel.class.getDeclaredField(fieldName);
						field.setAccessible(true);
						field.set(newModel, model.get(key));
					} catch (IllegalArgumentException | IllegalAccessException e) {
						logger.error("实体类成员变量'"+key+"':'"+model.get(key).getClass()+"'类型不匹配",e);
					} catch (Exception e) {
						logger.info("微信新增属性'"+key+"'，需要添加到实体类和数据库中");
					}
			}
			if(StringUtils.isBlank(newModel.getHeadImgUrl()) || newModel.getHeadImgUrl().equals("/0")){
				newModel.setHeadImgUrl(null);
			}
			insert(newModel);
			return newModel;
		}
		return null;
	}

	@Override
	public Integer insert(WxUserDetailedInfoModel model) {
		Integer id = null;
		if(null != model && StringUtils.isNotBlank(model.getOpenId())){
			WxUserDetailedInfoModel oldModel = getWxUserDetailedInfoByOpenId(model.getOpenId());
			if(null == oldModel){
				//插入数据
				super.insert(model);
				id = model.getId();
			}else{
				id = oldModel.getId();
				//判断数据是否变化
				Field[] fields = model.getClass().getDeclaredFields(); // 获取实体类的所有属性，返回Field数组
				boolean flag = false;
				for (Field field : fields) {
					String fieldName = field.getName();
					if(fieldName.equals("serialVersionUID")||fieldName.equals("id")){
						continue;
					}
					try {
						field.setAccessible(true); 
						//无变化则设置为null,不更新
						if(null!=field.get(model)){
							if(field.get(model).equals(field.get(oldModel))){
								field.set(model, null);
							}else{
								flag = true;
							}
						}
					}catch (IllegalArgumentException | IllegalAccessException e) {
						logger.error("实体类'"+model.getClass()+"'的成员变量'"+fieldName+"':'"+field.getType()+"'类型不匹配",e);
					}
				}
				
				//数据发生变化则更新变化字段
				if(flag){
					//更新数据
					model.setId(oldModel.getId());
					updateById(model);
				}
			}
		}
		
		return id;
	}

	@Override
	public WxUserDetailedInfoModel getWxUserDetailedInfoByWeixin(String wxNo, String code) {
		WxConfig wxConfig = TokenFactory.getWxConfig(wxNo);
		Map<String, Object> authMap=WxWeb.accessToken(TokenFactory.getWxConfig(wxNo),code);
		String openId=(String)authMap.get("openid");
		logger.debug("微信用户授权信息：{}",authMap);
		if (StringUtils.isNotBlank(openId)) {
			Map<String, Object> userMap=WxWeb.userInfo(wxConfig, openId,null);
			logger.debug("微信用户资料：{}",userMap);
			//添加或更新微信用户数据
			WxUserDetailedInfoModel wxUserDetailedInfoModel = insertWxUserDetailedInfo(userMap);
			return wxUserDetailedInfoModel;
		}
		return null;
	}
}
